package com.project.lx.gettxtfilename.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.project.lx.gettxtfilename.R;

/**
 * @author: X_Meteor
 * @description: 自定义ImageView，具有以下功能：
 * 1、圆角图片（通过自定义属性传值，设置圆角的大小）
 * 2、圆形头像
 * 3、圆形头像边框（通过自定义属性传值，设置边框颜色和宽度）
 * @version: V_1.0.0
 * @date: 2017/6/2 14:45
 * @company:
 * @email: lx802315@163.com
 */
public class CircleImageView extends ImageView {

    /**
     * 绘制图片的画笔
     */
    private Paint mPaint;

    /**
     * 绘制边框的画笔
     */
    private Paint mBorderPaint;

    /**
     * 圆角的角度
     */
    private float roundPx;

    /**
     * 是否为圆形
     */
    private boolean isCircle;

    /**
     * 是否带边框
     */
    private boolean isBorder;

    /**
     * 边框宽度
     */
    private float borderWidth;

    /**
     * 边框颜色
     */
    private int borderColor;

    public CircleImageView(Context context) {
        this(context, null);
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context, attrs);
    }

    /**
     * 初始化画笔和自定义属性
     *
     * @param context
     * @param attrs
     */
    private void initView(Context context, @Nullable AttributeSet attrs) {

        //初始化图片画笔
        mPaint = new Paint();

        //初始化边框画笔
        mBorderPaint = new Paint();

        mBorderPaint.setStrokeWidth(borderWidth);
        mBorderPaint.setColor(borderColor);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView);
        if (ta != null) {
            roundPx = ta.getDimension(R.styleable.CircleImageView_roundPx, 15f);
            isCircle = ta.getBoolean(R.styleable.CircleImageView_isCircle, false);
            isBorder = ta.getBoolean(R.styleable.CircleImageView_isBorder, false);
            borderWidth = ta.getDimension(R.styleable.CircleImageView_borderWidth, 50f);
            borderColor = ta.getColor(R.styleable.CircleImageView_borderColor, Color.WHITE);
            ta.recycle();
        }
    }

    /**
     * 获取圆形图片方法
     *
     * @param source
     * @return Bitmap
     * @author caizhiming
     */
    private Bitmap getCircleBitmap(Bitmap source) {

        //画布长度
        int length = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight();
        mPaint.setAntiAlias(true);

        //圆心X坐标
        float centerX = length / 2;
        //圆心Y坐标
        float centerY = length / 2;
        //半径
        float radius;

        Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(target);

        if (isBorder) {
            radius = length / 2;
            canvas.drawCircle(centerX, centerY, radius, mBorderPaint);
            mBorderPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(source, 0, 0, mPaint);
        } else {
            radius = length / 2 - borderWidth;
            canvas.drawCircle(centerX, centerY, radius, mPaint);
            mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
            canvas.drawBitmap(source, 0, 0, mPaint);
        }

        return target;
//
//        int length = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight();
//        mPaint.setAntiAlias(true);
//        Bitmap target = Bitmap.createBitmap(length, length, Bitmap.Config.ARGB_8888);
//        Canvas canvas = new Canvas(target);
//        canvas.drawCircle(length / 2, length / 2, length / 2, mPaint);
//        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
//        canvas.drawBitmap(source, 0, 0, mPaint);
//        return target;

    }

    /**
     * 获取圆角矩形图片方法
     *
     * @param bitmap
     * @param roundPx,一般设置成15
     * @return Bitmap
     * @author caizhiming
     */
    private Bitmap getRoundBitmap(Bitmap bitmap, float roundPx) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;

        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        canvas.drawARGB(0, 0, 0, 0);
        mPaint.setColor(color);

        canvas.drawRoundRect(rectF, roundPx, roundPx, mPaint);
        canvas.drawBitmap(bitmap, rect, rect, mPaint);
        return output;

    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();      //获取该imageView设置的src图片

        if (drawable != null) {

            Bitmap bitmap = drawableToBitmap(drawable);
            Bitmap b;

            if (isCircle) {
                b = getCircleBitmap(bitmap);
            } else {
                b = getRoundBitmap(bitmap, roundPx);
            }

            final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
            final Rect rectDest = new Rect(0, 0, getWidth(), getHeight());

            mPaint.reset();
            if (isBorder) {
                canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, b.getWidth() / 2 - borderWidth, mBorderPaint);
            }
            canvas.drawBitmap(b, rectSrc, rectDest, mPaint);

        } else {
            super.onDraw(canvas);
        }

    }

    public static Bitmap drawableToBitmap(Drawable drawable) {

        Bitmap bitmap = Bitmap.createBitmap(

                drawable.getIntrinsicWidth(),

                drawable.getIntrinsicHeight(),

                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888

                        : Bitmap.Config.RGB_565);

        Canvas canvas = new Canvas(bitmap);

        //canvas.setBitmap(bitmap);

        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

        drawable.draw(canvas);

        return bitmap;

    }
}
